<template>
<div :style="{ padding: '0 0 32px 32px' }">
  <h4 :style="{ marginBottom: '20px' }">{{ title }}</h4>
  <v-chart :forceFit="true" :height="height" :data="data" :onClick="handleClick" :scale="scale" >
    <v-tooltip :showTitle="false" :dataKey="dataKey"/>
    <v-axis/>
    <v-legend :dataKey="field" />
    <v-pie position="percent" :color="xField" :v-style="pieStyle" :label="labelConfig"/>
    <v-coord type="theta"/>
  </v-chart>
</div>
</template>

<script>
const DataSet = require('@antv/data-set')
import { ChartEventMixins } from './mixins/ChartMixins'

export default {
  name: 'Pie',
  mixins: [ChartEventMixins],
  props: {
    title: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 254
    },
    field: {
      type: String,
      default: 'count'
    },
    xField: {
      type: String,
      default: 'item'
    },
    dataSource: {
      type: Array,
      default: () => [
        { item: '示例一', count: 40 },
        { item: '示例二', count: 21 },
        { item: '示例三', count: 17 },
        { item: '示例四', count: 13 },
        { item: '示例五', count: 9 }
      ]
    }
  },
  data() {
    return {
      scale: [{
        dataKey: 'percent',
        min: 0,
        formatter: '.0%'
      }],
      pieStyle: {
        stroke: '#fff',
        lineWidth: 1
      },
      labelConfig: ['percent', {
        formatter: (val, item) => {
          return item.point[this.xField] + ': ' + item.point[this.field] + ', ' + val
        }
      }],
      dataKey: this.xField + '*percent'
    }
  },
  computed: {
    data() {
      const dv = new DataSet.View().source(this.dataSource)
      // 计算数据百分比
      dv.transform({
        type: 'percent',
        field: this.field,
        dimension: this.xField,
        as: 'percent'
      })
      return dv.rows
    }
  }
}
</script>
